package org.mogu;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.impl.client.DefaultHttpClient;
import org.mogu.control.Replay1;
import org.mogu.control.Replay16;
import org.mogu.control.Replay21;
import org.mogu.control.Replay5;
import org.mogu.control.Weibo10;
import org.mogu.control.Weibo11;
import org.mogu.control.Weibo15;
import org.mogu.control.Weibo9;
import org.mogu.control.inter.ReplayTextImg;
import org.mogu.db.ActiveUserHelper;
import org.mogu.db.DBhelper;
import org.mogu.service.GetSyncUrl;
import org.mogu.service.InfoService;
import org.mogu.service.InfoSync;
import org.mogu.staticvalue.Convert;
import org.mogu.tools.Imgtools;
import org.mogu.tools.UrlSync;
import org.mogu.tools.UserUtil;
import org.mogu.R;


import android.app.ActivityManager;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class Welcome extends ListActivity {
	DefaultHttpClient client;
	HttpResponse httpResponse;
	ActiveUserHelper auh;
	// SQLiteDatabase db;
	SQLiteDatabase readdb;
	
	String old;
	String newverson;
	String downloaduri;

	Welcome welcome;

//	String uname;
//	public String pwd;
	String updateTime;
	ContentValues value;
	// Button back;
	TextView title;
	Weibo15 weibocontent15;
	Weibo10 weibocontent10;
	Weibo11 weibocontent11;
	Weibo9 weibocontent9;
	Replay1 replay1;
	Replay5 replay5;
	Replay16 replay16;
	Replay21 replay21;
	RelativeLayout control;
	ListView list;

	TextView data;

	List<String> itemLabel;// 显示集合
	List<String> itemContent;// 显示集合
	List<String> itemCode;// 值集合
	Map<String, Map<String, String>> contentmap = new HashMap<String, Map<String, String>>();
	Map<String, String> courentContent = null;
	List<String> showItem;
	List<String> showItemLabel;
	int showItemIndex = -1;
	// static String uname;
	String key;

	String lastTimeDesc = "lastUpdateTime desc";
	String codeasc = "code";
	
	String noticecode=null;

	Map<String, List<String>> codemap = new HashMap<String, List<String>>();
	Map<String, ArrayAdapter> adapterMap = new HashMap<String, ArrayAdapter>();

	public static final int INDEX = Menu.FIRST + 1;
	public static final int RELOGIN = Menu.FIRST + 2;
	public static final int REFASH = Menu.FIRST + 3;
	public static final int ALLREFASH = Menu.FIRST + 4;

	public ProgressDialog myDialog = null;

	// private ServiceConnection serviceConnection=new ServiceConnection() {
	//
	// @Override
	// public void onServiceConnected(ComponentName name, IBinder service) {
	// countService = (IInfoService) service;
	// Log.i("Welcome", "on serivce connected ");
	// init();
	// }
	//
	// @Override
	// public void onServiceDisconnected(ComponentName name) {
	// countService = null;
	// }
	//
	// };
	// private IInfoService countService;
	public static final String msgs="正在下载数据，请稍候......";
	public static final String titles="正在同步";
	public void initDialog(String til,String msg){
		
		this.myDialog=new ProgressDialog(this);
		this.myDialog.setCancelable(false);
		if(msg==null){
			this.myDialog.setMessage(msgs);
		}else{
			this.myDialog.setMessage(msg);
		}
		if(til==null){
			this.myDialog.setTitle(titles);
		}else{
			this.myDialog.setTitle(til);
		}
		this.myDialog.setButton("取消",new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				
			}
		});
		this.myDialog.setButton2("下载新版本",new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				Intent intent = new Intent();

                intent.setAction("android.intent.action.VIEW");

                Uri content_uri_browsers = Uri.parse(downloaduri);

                intent.setData(content_uri_browsers);

                intent.setClassName("com.android.browser","com.android.browser.BrowserActivity");

                welcome.startActivity(intent);
				
			}
		});
//		this.myDialog.setOnDismissListener(new OnDismissListener() {
//			
//			public void onDismiss(DialogInterface dialog) {
//				welcome.refash();
//			}
//		});
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		auh = DBhelper.getDBHelper(this);
		Imgtools.welcome = this;
		welcome = this;
		UserUtil.getUser(welcome);
		Uri uri = this.getIntent().getData();
		if (uri != null) {
			String msg = null;
			String[] webname = uri.toString().split("\\?");
			if(webname[1].indexOf("msg")==0){
				msg=webname[1].substring(4);
			}
			if(webname[1].indexOf("code")==0){
				noticecode=webname[1].substring(5);
			}
			if (msg!=null){
				try {
					Toast.makeText(this, URLDecoder.decode(msg,"UTF-8"), 8000).show();
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
//					e.printStackTrace();
				}
			}
			
			if (webname.length>=3){
//				welcome.initDialog(null, null);
//				welcome.myDialog.show();
//				InfoSync infoSync = new InfoSync();
//				infoSync.syncw(this, auh, webname[2].split(";"));
				UrlSync urlSync;
				for (String weburi : webname[2].split(";")) {
					if("".equals(weburi)){
						continue;
					}
					urlSync=new UrlSync();
					urlSync.setNotice(false);
					urlSync.setUri(weburi);
					urlSync.setMaincode("main");
					urlSync.setSyncType(UrlSync.INFOALL);
					Convert.syncList.add(urlSync);
				}
				
			}
			
		}

		uri = Uri.parse("");
		
		try{
			init();
		}catch(Exception e){
			e.getMessage();
		}
			

		// this.bindService(new Intent("org.mogu.service.ContentService"),
		// this.serviceConnection, BIND_AUTO_CREATE);
		// serviceConnection =

	}

	public void init() {
		// Log.i("Welcome-count",String.valueOf(countService.getCount()));
		String lookcode =null;
		synchronized (InfoSync.class) {
		readdb = auh.getReadableDatabase();
		Cursor appverson = readdb
				.rawQuery(
						"select verson,newverson,uri from appverson where id=1",
						null);
		appverson.moveToFirst();
		while (!appverson.isAfterLast()) {
			old=appverson.getString(0);
			newverson=appverson.getString(1);
			downloaduri=appverson.getString(2);
			if(!old.equals(newverson)){
				initDialog("通知","监测到应用新版本。");
				myDialog.show();
			}
			
			break;
		}
		appverson.close();
		
		Cursor activelist = readdb
				.rawQuery(
						"select username,password,lookcode,showItemLabel,showItem from activeuser order by isactive desc",
						null);
		if (activelist.getCount() == 0) {
			activelist.close();
			// readdb.close();
			// auh.close();
			Intent mainIntent = new Intent(this, TMain.class);
			this.startActivity(mainIntent);
			this.finish();
			return;
		}
		activelist.moveToFirst();
		Convert.upwd = activelist.getString(1);
		if(!activelist.getString(0).equals(Convert.uname)){
			Convert.uname = activelist.getString(0);
			
			Convert.syncList.clear();
		}
		
		
		
		
		if(noticecode==null){
			lookcode=activelist.getString(2);
		}else{
			lookcode=noticecode;
		}
		activelist.close();
		
				
		
		}
		// 判断服务是否开启
				final String serviceClassName = "org.mogu.service.InfoService";
				ActivityManager mActivityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
				List<ActivityManager.RunningServiceInfo> mServiceList = mActivityManager
						.getRunningServices(300);
				Boolean start = false;
				for (int i = 0; i < mServiceList.size(); i++) {
					if (mServiceList.get(i).service.getClassName().equals(
							serviceClassName)) {
						start = true;
						break;
					}

				}
				if (!start) {
					Convert.flag+=1;
					Intent i = new Intent(this, InfoService.class);
					i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					this.startService(i);
					Log.e("infoservice", "~~");
					
					//Toast.makeText(this, Convert.flag, 4000).show();

				}
		GetSyncUrl getSyncUrl=new GetSyncUrl(auh);
		getSyncUrl.init();
		String[] codearr = { Convert.uname };
		showItem = new ArrayList<String>();
		showItemLabel = new ArrayList<String>();
		String tempcode=lookcode;
		while(!"".equals(tempcode)&&tempcode!=null){
			getContentByCode(tempcode,Convert.uname);
			if(contentmap.containsKey(tempcode)){
				showItem.add(contentmap.get(tempcode).get("code"));
				showItemLabel.add("".equals(contentmap.get(tempcode).get("title"))?contentmap.get(tempcode).get("content"):contentmap.get(tempcode).get("title"));
				tempcode=contentmap.get(tempcode).get("father");
				
			}
			
		}
		Collections.reverse(showItem);
		Collections.reverse(showItemLabel);
		this.showItemIndex = showItemLabel.size() - 1;
		int count=0;
		synchronized (InfoSync.class) {
		Cursor contentlist = readdb
				.rawQuery(
						"select code,title,content,type,replyType from content where level='1' and username=? ",
						codearr);
		 count = contentlist.getCount();
		contentlist.close();
		}

		if (count == 0) {
			// readdb.close();
			// auh.close();
			Intent mainIntent = new Intent(this, TMain.class);
			this.startActivity(mainIntent);
			this.finish();
			return;
		}

		setContentView(R.layout.welcome);
		// back=(Button)findViewById(R.id.back);
		title = (TextView) findViewById(R.id.title);
		weibocontent10 = (Weibo10) findViewById(R.id.weibocontent10);
		weibocontent10.setVisibility(View.GONE);
		weibocontent11 = (Weibo11) findViewById(R.id.weibocontent11);
		weibocontent11.setVisibility(View.GONE);
		weibocontent9 = (Weibo9) findViewById(R.id.weibocontent9);
		weibocontent9.setVisibility(View.GONE);
		weibocontent15 = (Weibo15) findViewById(R.id.weibocontent15);
		weibocontent15.setVisibility(View.GONE);
		replay1 = (Replay1) findViewById(R.id.replay1);
		replay1.setVisibility(View.GONE);
		replay5 = (Replay5) findViewById(R.id.replay5);
		replay5.setVisibility(View.GONE);
		replay16 = (Replay16) findViewById(R.id.replay16);
		replay16.setVisibility(View.GONE);
		replay21 = (Replay21) findViewById(R.id.replay21);
		replay21.setVisibility(View.GONE);
		list = getListView();

		if (this.showItemIndex >= 0) {
			title.setText(showItemLabel.get(showItemIndex));
			title.setVisibility(View.VISIBLE);
		}

//		activelist.close();
		if (lookcode != null && !"".equals(lookcode)) {
			// //
			String[] selectionArgs = { Convert.uname, lookcode };
			synchronized (InfoSync.class) {
			Cursor contentInReaded = readdb
					.rawQuery(
							"select code,title,content,replyType,maincode,level,father,lastUpdateTime from content where username=? and code=? order by code",
							selectionArgs);
			if (contentInReaded.getCount() > 0) {
				contentInReaded.moveToFirst();
				while (!contentInReaded.isAfterLast()) {
					setContent(contentInReaded);
					contentInReaded.moveToNext();
				}
			}
			contentInReaded.close();
			}
			// /
			String[] father = { Convert.uname, lookcode };
			showMainData(father);
			return;
		}
		showMainData(codearr);

	}

	public void showMainData(String[] father) {
		String order = codeasc;
		String clickcode = null;
		ContentValues userlookcode = new ContentValues();
		if (father.length == 1) {
			key = father[0];
			userlookcode.put("lookcode", "");
		} else {
			key = father[0] + father[1];
			clickcode = father[1];
			userlookcode.put("lookcode", father[1]);
			if (contentmap.get(father[1]) != null
					&& contentmap.get(father[1]).get("level").length() == 3) {
				order = lastTimeDesc;
			}
		}

		SQLiteDatabase wdb = auh.getWritableDatabase();
		String[] whereArg = { Convert.uname };
		 synchronized (InfoSync.class) {
		wdb.update("activeuser", userlookcode, "username=?", whereArg);
		 }
		// if(codemap.containsKey(key+"code")){
		// itemCode=codemap.get(key+"code");
		// itemLabel=codemap.get(key+"label");
		// setList();
		// return;
		// }

		if (getContentByCode(father, true, order) > 0) {
			setList(clickcode);
		} else {
			goBack();
		}

	}
	public void getContentByCode(String code,String username) {
		Cursor contentlist = null;
		try {
			synchronized (InfoSync.class) {
				readdb = auh.getReadableDatabase();
				String[] arr={username,code};
				
					contentlist = readdb
							.rawQuery(
									"select code,title,content,replyType,maincode,level,father,lastUpdateTime from content where username=? and code=?"
										, arr);

				if (contentlist.getCount() == 0) {
					contentlist.close();

				} else {
					

					contentlist.moveToFirst();
					while (!contentlist.isAfterLast()) {
						
						setContent(contentlist);
						contentlist.moveToNext();
					}
					contentlist.close();
				}
			}
		} catch (Exception t) {
			Log.e("Welcome", code.toString());
		} finally {
			// readdb.close();
			if (contentlist != null && !contentlist.isClosed()) {
				contentlist.close();
			}

		}
	}

	public int getContentByCode(String[] father, boolean b, String order) {
		int i = 0;
		Cursor contentlist = null;
		try {
			synchronized (InfoSync.class) {
				readdb = auh.getReadableDatabase();

				if (father.length == 1) {
					// back.setVisibility(View.GONE);
					title.setVisibility(View.VISIBLE);
					title.setText("蘑菇");

					contentlist = readdb
							.rawQuery(
									"select code,title,content,replyType,maincode,level,father,lastUpdateTime from content where level='1' and username=? order by code",
									father);
				} else {
					// back.setVisibility(View.VISIBLE);
					title.setVisibility(View.VISIBLE);
					// back.setImageResource(R.drawable.left);
					contentlist = readdb
							.rawQuery(
									"select code,title,content,replyType,maincode,level,father,lastUpdateTime,id from content where username=? and father=? order by "
											+ order, father);
				}

				if (contentlist.getCount() == 0) {
					contentlist.close();

				} else {
					// 显示的item
					if (b) {
						list.setVisibility(View.VISIBLE);
						itemLabel = new ArrayList<String>();
						itemContent = new ArrayList<String>();
						itemCode = new ArrayList<String>();
					}
					int iddel=0;
					contentlist.moveToFirst();
					while (!contentlist.isAfterLast()) {
						if (b) {
							itemCode.add(contentlist.getString(0));
							if (contentlist.getString(5).length() > 2) {
								itemLabel
										.add(contentlist.getString(2) == null ? ""
												: contentlist.getString(2));
							} else {
								itemLabel
										.add(contentlist.getString(1) == null ? ""
												: contentlist.getString(1));
							}

							itemContent.add(contentlist.getString(2));
						}
						setContent(contentlist);
						i++;
						if(i>=200){
							iddel=contentlist.getInt(8);
							break;
						}
						contentlist.moveToNext();
						
					}
					contentlist.close();
					if(i>=200&&iddel!=0){
						if(father.length>1&&contentmap.get(father[1]).get("level").equals("100")){
							readdb.execSQL("delete from content where father = '"
									+ father[1] + "' and username='" + father[0] + "' and id<"+iddel);
							
							Log.e("del", father[1]);
						}
					}
				}
			}
		} catch (Exception t) {
			Log.e("Welcome", father.toString());
		} finally {
			// readdb.close();
			if (contentlist != null && !contentlist.isClosed()) {
				contentlist.close();
			}

		}
		return i;
	}

	public void setContent(Cursor contentlist) {
		Map<String, String> content;
		if (!contentmap.containsKey(contentlist.getString(0))) {
			content = new HashMap<String, String>();

		} else {
			content = contentmap.get(contentlist.getString(0));
		}
		content.put("code", contentlist.getString(0));
		content.put("title", contentlist.getString(1));
		content.put("content", contentlist.getString(2));
		content.put("replyType", contentlist.getString(3));
		content.put("maincode", contentlist.getString(4));
		content.put("level", contentlist.getString(5));
		content.put("father", contentlist.getString(6));
		content.put("lastUpdateTime", contentlist.getString(7));
		contentmap.put(content.get("code"), content);

	}

	class ContentAdapter extends ArrayAdapter {
		ContentAdapter() {
			super(Welcome.this, R.layout.weclomelistrow, itemContent);
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View row = convertView;
			if (row == null) {
				LayoutInflater inflater = getLayoutInflater();
				row = inflater.inflate(R.layout.weclomelistrow, parent, false);
			}
			TextView label = (TextView) row.findViewById(R.id.label);
			label.setText(Imgtools.getContent(itemContent.get(position)));
			return (row);

		}
	}

	class WeiboAdapter extends ArrayAdapter {
		WeiboAdapter() {
			super(Welcome.this, R.layout.weibolistrow, itemCode);
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View row = convertView;
			if (row == null) {
				LayoutInflater inflater = getLayoutInflater();
				row = inflater.inflate(R.layout.weibolistrow, parent, false);
			}

			TextView label = (TextView) row.findViewById(R.id.label);
			TextView time = (TextView) row.findViewById(R.id.time);
			String type=contentmap.get(itemCode.get(position)).get(
					"replyType");
			boolean b=true;
			if ("3".equals(type)) {
				label.setText(Imgtools.getContent(
						contentmap.get(itemCode.get(position)).get("content"),
						label));
				b=false;
			} 
			if("16".equals(type)){
				label.setText(Imgtools.getContent(contentmap.get(
						itemCode.get(position)).get("content").split("\\n")[0]));
				b=false;
			}
			if("21".equals(type)){
				label.setText(Imgtools.getContent(contentmap.get(
						itemCode.get(position)).get("content").split("\\n")[0]));
				b=false;
			}
			if(b){

				label.setText(Imgtools.getContent(contentmap.get(
						itemCode.get(position)).get("content")));
			}

			time.setText(contentmap.get(itemCode.get(position))
					.get("lastUpdateTime").substring(0, 19));
			return (row);

		}
	}

	class ReplaySelectedAdapter extends ArrayAdapter {
		ReplaySelectedAdapter() {
			super(Welcome.this, R.layout.weiboshouquanrow, itemCode);
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View row = convertView;
			if (row == null) {
				LayoutInflater inflater = getLayoutInflater();
				row = inflater
						.inflate(R.layout.weiboshouquanrow, parent, false);
			}

			TextView label = (TextView) row.findViewById(R.id.label);
			// TextView time = (TextView) row.findViewById(R.id.time);
			String[] w = contentmap.get(itemCode.get(position)).get("content")
					.split("\\*\\*");
			String c;
			for (int i = 0; i < w.length; i++) {
				if (!"".equals(w[i])) {
					label.append(Imgtools.getContent(w[i] + "\n"));
				}
			}

			// time.setText(contentmap.get(itemCode.get(position)).get("lastUpdateTime").substring(0,
			// 19));
			return (row);

		}
	}

	class WeiboShouQuanAdapter extends ArrayAdapter {
		WeiboShouQuanAdapter() {
			super(Welcome.this, R.layout.weiboshouquanrow, itemCode);
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View row = convertView;
			if (row == null) {
				LayoutInflater inflater = getLayoutInflater();
				row = inflater
						.inflate(R.layout.weiboshouquanrow, parent, false);
			}

			TextView label = (TextView) row.findViewById(R.id.label);

			if ("5".equals(contentmap.get(itemCode.get(position)).get(
					"replyType"))) {
				label.setText(contentmap.get(itemCode.get(position))
						.get("content").replaceAll("#[0-9]*#", " \n请输入 \n"));
			}
			if ("15".equals(contentmap.get(itemCode.get(position)).get(
					"replyType"))) {

				String l = "未开通微博应用。";

				String[] w = contentmap.get(itemCode.get(position))
						.get("content").split("\\*;\\*");
				try {
					l = "";

					if (w.length > 0) {
						String[] ww = w[0].split("\\*");
						if (ww.length > 0) {
							for (int i = 0; i < ww.length; i++) {
								if ("1".equals(ww[i])) {
									l = l + "新浪微博,已开通。\n";
								}
								if ("2".equals(ww[i])) {
									l = l + "搜狐微博,已开通。\n";
								}
								if ("3".equals(ww[i])) {
									l = l + "网易微博,已开通。\n";
								}
								if ("4".equals(ww[i])) {
									l = l + "腾讯微博,已开通。\n";
								}
							}
						}
						ww = w[1].split("\\*");
						if (ww.length > 0) {
							for (int i = 0; i < ww.length; i++) {
								if ("1".equals(ww[i])) {
									l = l + "新浪微博,未开通。\n";
								}
								if ("2".equals(ww[i])) {
									l = l + "搜狐微博,未开通。\n";
								}
								if ("3".equals(ww[i])) {
									l = l + "网易微博,未开通。\n";
								}
								if ("4".equals(ww[i])) {
									l = l + "腾讯微博,未开通。\n";
								}
							}
						}
					}

				} catch (Exception e1) {
					Toast.makeText(
							welcome,
							contentmap.get(itemCode.get(position)).get(
									"content")
									+ ":数据不对。", 4000).show();
				}
				label.setText(l);
			}
			return (row);

		}
	}

	public void setList(String clickcode) {
		// setListAdapter(new ArrayAdapter<String>(this,
		// R.layout.weclomelistrow,R.id.label,itemLabel));
		if (clickcode == null) {
			courentContent = null;
		} else {
			courentContent = contentmap.get(clickcode);
		}

		if (adapterMap.containsKey(key)) {
			setListAdapter(adapterMap.get(key));
		} else {
			ArrayAdapter c = null;
			if (courentContent != null) {
				if (courentContent.get("level").length() >= 3) {
					if ("10".equals(courentContent.get("replyType"))
							|| "11".equals(courentContent.get("replyType"))
							|| "9".equals(courentContent.get("replyType"))
							|| "3".equals(courentContent.get("replyType"))) {
						c = new WeiboAdapter();
					}

					if ("15".equals(courentContent.get("replyType"))) {

						c = new WeiboShouQuanAdapter();
					}
					if ("16".equals(courentContent.get("replyType"))) {

						c = new WeiboAdapter();
					}
					if ("21".equals(courentContent.get("replyType"))) {
						
						c = new WeiboAdapter();
					}
					if ("5".equals(courentContent.get("replyType"))) {

						// c = new WeiboShouQuanAdapter();
						onListItemClick(null, null, 0, 0);
					}
					if ("1".equals(courentContent.get("replyType"))
							|| "2".equals(courentContent.get("replyType"))) {

						// c = new ReplaySelectedAdapter();
						onListItemClick(null, null, 0, 0);
					}
				}

			}
			if (c == null) {
				if ("100".equals(contentmap.get(itemCode.get(0)).get("level"))) {
					onListItemClick(null, null, 0, 0);
					return;
				}

				c = new ContentAdapter();
			}
			setListAdapter(c);
			// adapterMap.put(key, c);
		}

	}
	public void gotoImageGroup(){
		 /*new一个Intent对象，并指定class*/ 
        Intent intent = new Intent();  
        intent.setClass(welcome,ImageGroup.class);  
          
//        /*new一个Bundle对象，并将要传递的数据传入*/ 
//        Bundle bundle = new Bundle();  
//        bundle.putDouble("height",height);  
//        bundle.putString("sex",sex);  
//        
//        /*将Bundle对象assign给Intent*/ 
//        intent.putExtras(bundle);  
        
        /*调用Activity EX03_11_1*/ 
        startActivityForResult(intent,0);  
	}
	/* 覆盖 onActivityResult()*/ 
	  @Override 
	  protected void onActivityResult(int requestCode, int resultCode,  
	                                  Intent data)  
	  {  
	    switch (resultCode)  
	    {   
	      case RESULT_OK:  
	        /* 取得来自Activity2的数据，并显示于画面上 */    
	        Bundle bunde = data.getExtras();  
	        String str = bunde.getString("data");  
//	        double height = bunde.getDouble("height");  
	        Toast.makeText(welcome, str, Toast.LENGTH_SHORT)
			.show();// 显示信息;
	        ReplayTextImg r=null;
	        try{
	        	r=(ReplayTextImg) control;
	        }catch(Exception e){
	        	e.getMessage();
	        }
	        
	        if(r!=null){
	        	r.addImg(str);
	        }
	        break;  
	      default:  
	        break;  
	     }   
	   }   

	public void goBack() {
		if (control == null || control.getVisibility() == View.GONE) {
			if (showItemIndex > -1) {
				showItem.remove(showItemIndex);
				showItemLabel.remove(showItemIndex);
				showItemIndex--;
				refash();
			}

		} else {
			control.setVisibility(View.GONE);
			list.setVisibility(View.VISIBLE);
			if ("1".equals(courentContent.get("replyType"))
					|| "2".equals(courentContent.get("replyType"))
					|| "5".equals(courentContent.get("replyType"))) {
				goBack();
			}
		}
	}

	public void refash() {
		try {
			if (showItemIndex < 0) {
				String[] codearr = { Convert.uname };
				showMainData(codearr);
				return;
			}
			title.setText(showItemLabel.get(showItemIndex));
			String[] father = { Convert.uname, showItem.get(showItemIndex) };
			showMainData(father);
		} catch (Exception e) {
			e.getMessage();
		}
	}

	public void onListItemClick(ListView parent, View v, int position, long id) {
		// Toast.makeText(this,
		// itemLabel.get(position) + ":" + itemCode.get(position), 4000)
		// .show();
		String[] father = { Convert.uname, itemCode.get(position) };
		courentContent = contentmap.get(itemCode.get(position));
		if (courentContent.get("level") != null
				&& courentContent.get("level").length() < 3) {
			showItemLabel.add(itemLabel.get(position));
			showItem.add(father[1]);
			title.setText(itemLabel.get(position));
			showItemIndex++;
		}

		if ("101".equals(courentContent.get("level"))
				&& "10".equals(courentContent.get("replyType"))) {
			weibocontent10.setVisibility(View.VISIBLE);
			weibocontent10.setContent(courentContent.get("code"),
					courentContent.get("replyType"),
					courentContent.get("maincode"), 
					courentContent.get("content"));
			weibocontent10.setWeibo10(weibocontent10, this);
			control = weibocontent10;
			list.setVisibility(View.GONE);
			return;

		}
		if ("101".equals(courentContent.get("level"))
				&& "11".equals(courentContent.get("replyType"))) {
			weibocontent11.setVisibility(View.VISIBLE);
			weibocontent11.setContent(courentContent.get("code"),
					courentContent.get("replyType"),
					courentContent.get("maincode"), 
					courentContent.get("content"));
			weibocontent11.setWeibo11(weibocontent11, this);
			control = weibocontent11;
			list.setVisibility(View.GONE);
			return;
		}
		if ("101".equals(courentContent.get("level"))
				&& "9".equals(courentContent.get("replyType"))) {
			weibocontent9.setVisibility(View.VISIBLE);
			weibocontent9.setContent(courentContent.get("code"),
					courentContent.get("father"),
					courentContent.get("replyType"),
					courentContent.get("maincode"), 
					courentContent.get("content"));
			weibocontent9.setWeibo9(weibocontent9, this);
			control = weibocontent9;
			list.setVisibility(View.GONE);
			return;
		}
		if ("101".equals(courentContent.get("level"))
				&& "15".equals(courentContent.get("replyType"))) {
			weibocontent15.setVisibility(View.VISIBLE);
			weibocontent15.setContent(courentContent.get("code"),
					courentContent.get("father"),
					courentContent.get("replyType"),
					courentContent.get("maincode"), 
					courentContent.get("content"));
			weibocontent15.setWeibo15(weibocontent15, this);
			control = weibocontent15;
			list.setVisibility(View.GONE);
			return;
		}
		if ("101".equals(courentContent.get("level"))
				&& ("1".equals(courentContent.get("replyType")) || "2"
						.equals(courentContent.get("replyType")))) {
			replay1.setVisibility(View.VISIBLE);
			replay1.setContent(courentContent.get("code"),
					courentContent.get("father"),
					courentContent.get("replyType"),
					courentContent.get("maincode"), 
					courentContent.get("content"));
			replay1.setReplay(replay1, this);
			control = replay1;
			list.setVisibility(View.GONE);
			return;
		}
		if ("101".equals(courentContent.get("level"))
				&& "5".equals(courentContent.get("replyType"))) {
			replay5.setVisibility(View.VISIBLE);
			replay5.setContent(courentContent.get("code"),
					courentContent.get("father"),
					courentContent.get("replyType"),
					courentContent.get("maincode"), 
					courentContent.get("content"));
			replay5.setReplay(replay5, this);
			control = replay5;
			list.setVisibility(View.GONE);
			return;
		}
		if ("101".equals(courentContent.get("level"))
				&& "16".equals(courentContent.get("replyType"))) {
			replay16.setVisibility(View.VISIBLE);
			replay16.setContent(courentContent.get("code"),
					courentContent.get("father"),
					courentContent.get("replyType"),
					courentContent.get("maincode"), 
					courentContent.get("content"));
			replay16.setReplay(replay16, this);
			boolean b = false;

			String[] arr = { Convert.uname, courentContent.get("code") };
			if (getContentByCode(arr, false, codeasc) == 0
					|| contentmap.get(courentContent.get("code") + "-" + Convert.uname) == null
					|| "0".equals(contentmap.get(
							courentContent.get("code") + "-" + Convert.uname).get(
							"content"))) {
				b = true;
			}
			replay16.setButtonView(b);
			control = replay16;
			list.setVisibility(View.GONE);
			return;
		}
		if ("101".equals(courentContent.get("level"))
				&& "21".equals(courentContent.get("replyType"))) {
			replay21.setVisibility(View.VISIBLE);
			replay21.setContent(courentContent.get("code"),
					courentContent.get("father"),
					courentContent.get("replyType"),
					courentContent.get("maincode"), 
					courentContent.get("content"));
			replay21.setReplay(replay21, this);
			control = replay21;
			list.setVisibility(View.GONE);
			return;
		}
		if ("101".equals(courentContent.get("level"))
				&& "3".equals(courentContent.get("replyType"))) {

			return;
		}

		showMainData(father);

	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0
				&& showItemIndex > -1) { // 按下的如果是BACK，同时没有重复

			goBack();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenu.ContextMenuInfo menuInfo) {
		populateMenu(menu);
	}

	public void populateMenu(Menu menu) {
		menu.add(Menu.NONE, INDEX, Menu.NONE, "首页");
		menu.add(Menu.NONE, RELOGIN, Menu.NONE, "重新登录");
		menu.add(Menu.NONE, REFASH, Menu.NONE, "刷新");
		menu.add(Menu.NONE, ALLREFASH, Menu.NONE, "反馈意见");
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		populateMenu(menu);
		return (super.onCreateOptionsMenu(menu));
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		return (applyMenuChoice(item) || super.onOptionsItemSelected(item));
	}

	public boolean onContextItemSelected(MenuItem item) {
		return (applyMenuChoice(item) || super.onContextItemSelected(item));
	}
	
	public void sendSuggest(){
		Intent email = new Intent(android.content.Intent.ACTION_SEND);
		email.setType("plain/text");
		String[] emailReciver = new String[]{"moguzx@gmail.com"};
		String emailSubject = "";
		String emailBody = "您对我们的应用有何建议，请发送邮件联系我们。\n"+"用户名:"+Convert.uname+"\n";

		//设置邮件默认地址
		email.putExtra(android.content.Intent.EXTRA_EMAIL, emailReciver);
		//设置邮件默认标题
		email.putExtra(android.content.Intent.EXTRA_SUBJECT, emailSubject);
		//设置要默认发送的内容
		email.putExtra(android.content.Intent.EXTRA_TEXT, emailBody);
		//调用系统的邮件系统
		startActivity(Intent.createChooser(email, "请选择邮件发送软件"));
	}

	public boolean applyMenuChoice(MenuItem item) {
		switch (item.getItemId()) {
		case INDEX:
			String[] codearr = { Convert.uname };
			showMainData(codearr);
			return true;
		case RELOGIN:
			new Handler().postDelayed(new Runnable() {
				public void run() {
					Intent mainIntent = new Intent(Welcome.this, TMain.class);
					Welcome.this.startActivity(mainIntent);
					Welcome.this.finish();
					overridePendingTransition(android.R.anim.slide_in_left,
							android.R.anim.slide_out_right);
				}
			}, 1500);
			return true;
		case REFASH:
			refash();
			Toast.makeText(this, "刷新了当前页面。", 4000).show();
//			InfoSync infoSync=new InfoSync();
//			String[] uri={Convert.hosturl.substring(7)+"/InfoAll"};
//			infoSync.syncw(welcome, DBhelper.getDBHelper(welcome), uri);
			return true;
		case ALLREFASH:
			sendSuggest();
			// refash();
			//Toast.makeText(this, "正在同步。（功能尚未开发）", 4000).show();
			return true;
		}
		return false;
	}
}
